<?php

namespace cccmvc;

class Request
{
    public function getPath(): string
    {
        $path = $_SERVER['REQUEST_URI'] ?? '/';

        $index = strpos($path, '?');

        if ($index !== false) {
            $path = substr($path, 0, $index);
        }

        return ltrim($path, '/index.php');
    }

    public function getMethod(): string
    {
        return $_SERVER['REQUEST_METHOD'] ?? 'GET';
    }

    public function isGet(): bool
    {
        return $this->getMethod() === "GET";
    }

    public function isPost(): bool
    {
        return $this->getMethod() === "POST";
    }

    public function all(): array
    {
        $data = [];
        if ($this->isGet()) {
            foreach ($_GET as $key => $value) {
                $data[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS);
            }
        }
        if ($this->isPost()) {
            foreach ($_POST as $key => $value) {
                $data[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
            }
        }

        return $data;
    }

    public function input($key, $default = '')
    {
        return $this->all()[$key] ?? $default;
    }
}